import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import type { RouteRecordNormalized, RouteLocationNormalized } from 'vue-router'

// Tab页数据结构
interface TabItem {
  path: string
  name?: string
  title: string
  componentName?: string
}

export const useAppStore = defineStore(
  'app',
  () => {
    // 路由实例
    const router = useRouter()
    // 侧边栏是否折叠
    const sidebarCollapsed = ref(false)

    // 设备类型
    const device = ref<'desktop' | 'mobile'>('desktop')

    // 窗口大小
    const windowSize = ref({
      width: window.innerWidth,
      height: window.innerHeight
    })

    // 缓存的Tab列表
    const cachedTabs = ref<TabItem[]>([])

    // 当前激活的Tab
    const activeTab = ref('')

    /**
     * 切换侧边栏折叠状态
     */
    const toggleSidebar = () => {
      sidebarCollapsed.value = !sidebarCollapsed.value
    }

    /**
     * 设置侧边栏折叠状态
     */
    const setSidebarCollapsed = (collapsed: boolean) => {
      sidebarCollapsed.value = collapsed
    }

    /**
     * 设置设备类型
     */
    const setDevice = (type: 'desktop' | 'mobile') => {
      device.value = type
    }

    /**
     * 添加Tab
     */
    const addTab = (route: RouteLocationNormalized) => {
      const { path, name, meta } = route
      
      // 忽略不需要缓存的路由
      if (!meta?.title || meta?.isHidden || path === '/login') return
      
      // 检查是否已存在该Tab
      const existingTab = cachedTabs.value.find(tab => tab.path === path)
      if (!existingTab) {
        cachedTabs.value.push({
          path,
          name: name as string,
          title: meta.title as string,
          componentName: meta.title as string
        })
      }
      
      // 设置当前激活的Tab
      activeTab.value = path
    }

    /**
     * 移除Tab
     */
    const removeTab = (path: string) => {
      const index = cachedTabs.value.findIndex(tab => tab.path === path)
      if (index > -1) {
        cachedTabs.value.splice(index, 1)
        // 如果移除后没有标签页了，跳转到首页
        if (cachedTabs.value.length === 0) {
          router.push('/home')
        } else if (activeTab.value === path) {
          // 如果移除的是当前激活的Tab，则激活上一个或第一个Tab
          if (index > 0) {
            activeTab.value = cachedTabs.value[index - 1].path
          } else {
            activeTab.value = cachedTabs.value[0].path
          }
        }
      }
    }

    /**
     * 移除其他Tab
     */
    const removeOtherTabs = (path: string) => {
      const tab = cachedTabs.value.find(tab => tab.path === path)
      if (tab) {
        cachedTabs.value = [tab]
        activeTab.value = path
      }
    }

    /**
     * 移除所有Tab并跳转到home（保留home在缓存中）
     */
    const removeAllTabs = () => {
      // 清空所有标签页，只保留home在缓存中
      cachedTabs.value = [{ path: '/home', name: 'Home', title: '首页', componentName: 'Home' }]
      activeTab.value = '/home'
      // 跳转到首页
      router.push('/home')
    }

    /**
     * 更新窗口大小
     */
    const updateWindowSize = () => {
      windowSize.value = {
        width: window.innerWidth,
        height: window.innerHeight
      }

      // 根据窗口宽度自动设置设备类型
      if (window.innerWidth < 768) {
        setDevice('mobile')
        setSidebarCollapsed(true)
      } else {
        setDevice('desktop')
      }
    }

    // 监听窗口大小变化
    if (typeof window !== 'undefined') {
      window.addEventListener('resize', updateWindowSize)
      updateWindowSize()
    }

    return {
      sidebarCollapsed,
      device,
      windowSize,
      cachedTabs,
      activeTab,
      toggleSidebar,
      setSidebarCollapsed,
      setDevice,
      updateWindowSize,
      addTab,
      removeTab,
      removeOtherTabs,
      removeAllTabs
    }
  },
  {
    persist: {
      key: 'app',
      storage: localStorage,
      pick: ['sidebarCollapsed', 'cachedTabs', 'activeTab']
    }
  }
)
